<?php


namespace App\Http\Repositories\xinStore;


use App\Exceptions\ApiException;
use App\Http\Repositories\BaseRepository;
use App\Models\StoreCenter\Models\CouponModel;
use App\Models\StoreCenter\Models\CouponUserModel;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;

class CouponRepository extends BaseRepository
{
    const CACHE_KEY = 'xin:store:coupon_user:';
    public $coupon;
    public $couponUser;
    public function __construct(CouponUserModel $couponUserModel, CouponModel $couponModel)
    {
        $this->coupon = $couponModel;
        $this->couponUser = $couponUserModel;
    }

    /**
     * 验证领取规则
     * @param $data
     * @throws ApiException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function couponValidator($data)
    {
        $totalKey = CouponModel::TOTAL_CACHE.$data['coupon_code'];
        $usedKey = CouponModel::USED_CACHE.$data['coupon_code'];
        is_real_exists(@$data['start_time']) && $start = strtotime($data['start_time']);
        is_real_exists(@$data['expire_time']) && $expire = strtotime($data['expire_time']);

        if(isset($start) && $start >= time())
            $this->throwError([0, '未到领取时间']);
        if(isset($expire) && $expire <= time())
            $this->throwError([0, '已过领取时间']);

        if ($data['total'] != 0) {
            $total = Cache::get($totalKey);

            if (is_null($total)) {
                $count = $this->couponUser->where('coupon_code', $data['coupon_code'])->count();
                if ($count >= $data['total']) {
                    $this->throwError([0, '已领完']);
                }
                Cache::set($totalKey, ($data['total']-1));
            } else {
                if ($total <= 0) {
                    $this->throwError([0, '已领完']);
                } else {
                    Cache::decrement($totalKey);
                }
            }
        }

        if ($data['count'] != 0) {
            $used = Cache::get($usedKey);

            if (is_null($used)) {
                $where[] = ['coupon_code', $data['coupon_code']];
                $where[] = ['create_user_uuid', $data['coupon_code']];
                $count = $this->couponUser->handleCondition($where)->count();
                if ($count >= $data['count']) {
                    $this->throwError([0, '已领取']);
                }
                Cache::set($usedKey, ($data['count']-1));
            } else {
                if ($used <= 0) {
                    $this->throwError([0, '已领取']);
                } else {
                    Cache::decrement($usedKey);
                }
            }
        }

    }

    /**
     * 领取优惠券
     * @param $data
     * @return mixed
     * @throws ApiException
     */
    public function addCoupon($data)
    {
        $this->couponValidator($data);

        return $this->couponUser->addItem($data, true);

    }

    /**
     * 获取优惠券详情
     * @param $data
     * @return mixed
     * @throws ApiException
     */
    public function getCouponInfo($data)
    {
        if (isset($data['id']))
            $where['id'] = $data['id'];
        else
            $where['code'] = $data['code'];

        return $this->couponUser->getInfo($where);
    }

    /**
     * 获取优惠券列表
     * @param $data
     * @return mixed
     */
    public function getCouponList($data)
    {
        $key = self::CACHE_KEY.getCurrentUserId();

        if (Cache::has($key)) {
            return getCache($key);
        }

        $where['create_user_uuid'] = getCurrentUserId();
        is_real_exists(@$data['type']) && $where['create_user_uuid'] =  $data['create_user_uuid'];
        is_real_exists(@$data['condition']) && $where['start_time'] = ['between', $data['start_time']];
        is_real_exists(@$data['store_id']) && $where['condition'] = $data['condition'];

        $res = $this->couponUser->getListByPage($where)->toArray();

        setRedis($key, $res);

        return $res;
    }

}
